#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <pthread.h>
#include "thread.h"
#include "initM0.h"

void *threadFunc(void *arg)
{
	//线程间通信
    int M0fd = initM0();        
	int connfd = *((int *)arg);
	char buf[1024];
	while(1)
	{
        int ret;
		memset(buf, 0, sizeof(buf));
		ret = recv(connfd, buf, sizeof(buf), MSG_DONTWAIT);
        if(ret > 0)
        {
            printf("ret = %d \r\n");
            M0_command(M0fd,buf);
		    printf("recv from client:%s\n",buf);
        }
		printf("recv from client:%s\n",buf);
		memset(buf, 0, sizeof(buf));
        M0_recv(M0fd,buf);
        printf("---------------%s\r\n",buf);
		ret = send(connfd, buf, sizeof(buf), 0);
		if(ret < 0)
		{
			perror("send error!\n");
			//close(connfd);
			//return (void *)-1;
		    break;
        
        }
	}
    close(M0fd);
	close(connfd);
	pthread_exit(NULL);
}
int initServer()
{
	//创建套接字
	int servFd = socket(PF_INET, SOCK_STREAM, 0);
	if(servFd < 0)
	{
		perror("socket error!\n");
		return -1;
	}
	printf("socket ok!\n");
	struct sockaddr_in servAddr;
	memset(&servAddr, 0, sizeof(servAddr));
	servAddr.sin_family = PF_INET;
	servAddr.sin_port = htons(8888);
	servAddr.sin_addr.s_addr = inet_addr("192.168.1.233");
    int on = 1;
    if((setsockopt(servFd,SOL_SOCKET,SO_REUSEADDR,&on,sizeof(on)))<0) //避免多次启动，服务器地址被占用 
    {  
        perror("setsockopt failed");  
        exit(0);  
    }  
	//绑定地址信息
	int ret = bind(servFd, (struct sockaddr *)&servAddr, sizeof(servAddr));
	if(ret < 0)
	{
		perror("bind error!\n");
		close(servFd);
		return -1;
	}
	printf("bind ok!\n");
	//创建监听队列
	ret = listen(servFd, 20);
	if(ret < 0)
	{
		perror("listen error!\n");
		close(servFd);
		return -1;
	}
	printf("listen ok!\n");
	return servFd;
}

int waitAccept(int servFd)
{
	//创建监听套接字
	int connfd = accept(servFd, NULL, NULL);
	if(connfd < 0)
	{
		perror("accept error!\n");
		close(servFd);
		return -1;
	}
	printf("accept ok!\n");
	return connfd;
}

int exitServer(int servFd, int connfd)
{
	//关闭套接字
	close(servFd);
	close(connfd);
}


